import re


def extract_content_between_brackets(s: str, start: int = 0):
    stack = []
    result = []
    in_brackets = False

    for i in range(start, len(s)):
        char = s[i]

        if char == "(":
            stack.append(i)
            in_brackets = True
        elif char == ")":
            if stack:
                start_index = stack.pop()
                if not stack:  # If the stack is empty, we found the matching pair
                    end = i
                    result.append(s[start_index + 1 : i])

    return result, end


def extract_variable_pairs(s):
    # 使用正则表达式匹配变量名及其可能包含的括号
    pattern = re.compile(r"(\w[\w\s]*\([^)]*\)|\w+):(\w[\w\s]*\([^)]*\)|\w+)")

    # 查找所有匹配的对
    matches = pattern.findall(s)

    # 如果没有匹配项，返回空列表
    if not matches:
        return f"({s})"

    # 将结果整理为所需格式
    result = []
    for match in matches:
        result.append(f"({match[0]}, {match[1]})")

    return f".slice(dimension{'.dim'.join(result)})"


def deal_with_dims(s):
    start = s.find("(")
    if start == -1:
        return s

    contents_in_brackets, end = extract_content_between_brackets(s, start=start)

    result = s[:start]

    for content in contents_in_brackets:
        result += extract_variable_pairs(content)
    
    result += s[end + 1:]

    return result


text = "foobar(blabla)(f1:x,foo(bar,3):y,z(3):a(b))ffoobar"
print(deal_with_dims(text))

text = "program main"
print(deal_with_dims(text))
